from django.contrib import messages
from django.contrib.auth.decorators import permission_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.models import Group, User
from django.http import HttpResponse, Http404, HttpResponseNotFound, HttpResponseRedirect
from django.shortcuts import render

# Create your views here.
from django.template import loader
from django.views.decorators.csrf import csrf_exempt

from django.views.generic import CreateView, DetailView

from jobs.forms import ResumeForm
from jobs.models import Job, JobCity, JobTypes, Resume
import html, logging

logger = logging.getLogger(__name__)


def joblist(request):
    job_list = Job.objects.order_by('job_type')
    # template = loader.get_template('joblist.html')
    context = {'job_list': job_list}  # 注意模板需要字典形式变量导入

    for job in job_list:
        job.type_name = JobTypes[job.job_type][1]  # 为job对象添加不存在属性;结尾序号是取有序元祖值
        job.city_name = JobCity[job.job_city][1]

    # return HttpResponse(template.render(context))  # 无request对象，没有页面上下文,无法渲染user对象
    return render(request, 'joblist.html', context)


def detail(request, job_id):
    try:
        job = Job.objects.get(pk=job_id)
        job.city_name = JobCity[job.job_city][1]
        logger.info("job info fetched from db job_id:%s" % job_id)
    except Job.DoesNotExist:
        # raise HttpResponseNotFound()
        raise Http404("Job does not exist")  # HttpResponseNotFound不 derive from BaseException

    context = {"job": job}

    return render(request, 'job.html', context)


'''
    直接返回  HTML 内容的视图 （这段代码返回的页面有 XSS 漏洞，能够被攻击者利用）
    使用django本身的通用视图或者render渲染后返回的内容可以防xss脚本攻击(将html,js等自动转义原始文本)
'''


def detail_resume(request, resume_id):
    try:
        resume = Resume.objects.get(pk=resume_id)
        content = "name:%s <br> introduction:%s <br>" % (
            resume.username, resume.candidate_introduction)
        logger.info("resume info fetched from db resume_id:%s" % resume_id)
        return HttpResponse(content)
        # return HttpResponse(html.escape(content))  # html.escape转义
    except Resume.DoesNotExist:
        raise Http404("Resume does not exist")


"""
演示csrf攻击,模拟管理员创建hr用户(这个 URL 仅允许有 创建用户权限的用户即admin访问)
"""


# @csrf_exempt  # 去除csrf_token校验
@permission_required('auth.add_user')
def create_hr_user(request):
    if request.method == 'GET':
        return render(request, 'create_hr.html', {})
    elif request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        hr_group = Group.objects.get(name='hr')
        user = User(is_superuser=False, username=username,
                    is_active=True, is_staff=True)
        user.set_password(password)
        user.save()
        user.groups.add(hr_group)

        messages.add_message(request, messages.INFO, 'user created %s' % username)

        return render(request, 'create_hr.html')
    else:
        return render(request, 'create_hr.html')


class ResumeCreateView(LoginRequiredMixin, CreateView):
    """创建职位简历页面"""
    template_name = 'resume_form.html'
    model = Resume
    success_url = '/joblist/'
    fields = ["username", "city", "phone",
              "email", "apply_position", "gender","picture","attachment",
              "bachelor_school", "master_school", "major", "degree",
              "candidate_introduction", "work_experience", "project_experience"]

    def post(self, request, *args, **kwargs):  # 重写CreateView中Post方法
        form = ResumeForm(request.POST, request.FILES)
        if form.is_valid():
            # <process form cleaned data>
            form.save()
            return HttpResponseRedirect(self.success_url)

        return render(request, self.template_name, {'form': form})

    # 从url传参带入城市，应聘职位等值
    def get_initial(self):
        initial = {}
        for x in self.request.GET:
            initial[x] = self.request.GET[x]
        return initial

    # 简历跟当前用户关联
    # TODO 前台登录用户通过resume/add/页面申请的简历无法保存申请人为请求的登录用户　124
    def form_valid(self, form):
        # self.object = form.save(commit=True)  # 验证表单
        self.object = form.save(commit=False)  # 验证表单
        self.object.applicant = self.request.user
        self.object.save()
        return HttpResponseRedirect(self.get_success_url())


class ResumeDetailView(DetailView):
    """创建职位简历页面"""
    template_name = 'resume_detail.html'
    model = Resume
